package user

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"shopping/config"
	"shopping/model"
	"shopping/service"
	"shopping/utils/api_helper"
	"shopping/utils/jwt_helper"
	"strconv"
	"time"
)

type Controller struct {
	userService *service.UserService
}

// NewUserController 实例化
func NewUserController(userService *service.UserService) *Controller {
	return &Controller{
		userService: userService,
	}
}

// CreateUser 创建用户
// @Summary 根据给定的用户名和密码创建用户
// @Tags Auth
// @Accept json
// @Produce json
// @Param CreateUserRequest body CreateUserRequest true "user information"
// @Success 201 {object} CreateUserResponse
// @Failure 500 {object} map[string]interface{}
// @Router /user [post]
func (controller *Controller) CreateUser(c *gin.Context) {
	var req CreateUserRequest
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"success": false,
			"message": "获取参数失败",
			"code":    500,
			"result":  nil,
		})
		return
	}
	newUser := model.NewUser(req.Username, req.Password, req.Password2)
	err := controller.userService.Create(newUser)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"success": false,
			"message": err.Error(),
			"code":    500,
			"result":  nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"success": false,
		"message": err.Error(),
		"code":    200,
		"result": CreateUserResponse{
			Username: req.Username,
		},
	})
}

// Login 登录
// @Summary 根据用户名和密码登录
// @Tags Auth
// @Accept json
// @Produce json
// @Param LoginRequest body LoginRequest true "user information"
// @Success 200 {object} LoginResponse
// @Failure 400 {object} api_helper.ErrorResponse
func (c *Controller) Login(g *gin.Context) {
	// 获取请求参数
	var req LoginRequest
	if err := g.ShouldBind(&req); err != nil {
		api_helper.HandleError(g, api_helper.ErrInvolidBody)
		return
	}
	// 查询用户信息
	currentUser, err := c.userService.GetUser(req.Username, req.Password)
	if err != nil {
		api_helper.HandleError(g, err)
		return
	}
	// 校验token
	decodeClaims := jwt_helper.VerifyToken(currentUser.Token, config.Conf.JwtConfig.SecretKey)
	if decodeClaims == nil {
		// 创建token中的
		jwtClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
			"userId":   strconv.FormatInt(currentUser.Id, 10), //int64 转 十进制字符串
			"username": currentUser.Username,
			"iat":      time.Now().Unix(), // 获取当前时间的时间戳 int64类型
			"iss":      os.Getenv("ENV"),
			"exp":      time.Now().Add(24 * time.Hour).Unix(),
			"isAdmin":  currentUser.IsAdmin,
		})
		// 创建token
		token := jwt_helper.GenerateToken(jwtClaims, config.Conf.JwtConfig.SecretKey)
		// 更新token
		currentUser.Token = token
		// 更新用户信息
		err := c.userService.UpdateUser(&currentUser)
		if err != nil {
			api_helper.HandleError(g, err)
			return
		}
	}
	g.JSON(http.StatusOK, LoginResponse{
		Username: currentUser.Username,
		Id:       currentUser.Id,
		Token:    currentUser.Token,
	})
}

// VerifyToken 验证token
func (c *Controller) VerifyToken(g *gin.Context) {
	token := g.GetHeader("Authorization")
	decodedClaims := jwt_helper.VerifyToken(token, config.Conf.JwtConfig.SecretKey)
	g.JSON(http.StatusOK, decodedClaims)
}
